import { _decorator, Component, Node, Collider2D, Contact2DType, IPhysics2DContact, Animation, Director, director, AudioClip, AudioSource, } from 'cc';
import { Player } from './Player/Player';
import { Enemy } from './Enemy/Enemy';
import { AudioManager } from './Runtime/AudioManager';
const { ccclass, property } = _decorator;

@ccclass('Weapon')
export class Weapon extends Component {
    private collider: Collider2D | null = null;
    private animation: Animation | null = null;
    @property(AudioSource)
    public audioSource: AudioSource = null;

    @property(AudioClip)
    public useWeaponClip: AudioClip = null;

    start() {
        this.collider = this.getComponent(Collider2D);
        if (this.collider) {
            this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
        this.animation = this.getComponent(Animation);

    }

    onBeginContact(self: Collider2D, other: Collider2D, contact: IPhysics2DContact) {
        if (other.node.name === "Enemy" || other.node.name === "Boss") {
            const enemy = other.node.getComponent(Enemy);
            if (enemy && !enemy.isDead) {
                director.once(Director.EVENT_AFTER_PHYSICS, () => {
                    this.audioSource.playOneShot(this.useWeaponClip, 0.2)
                    enemy.TakeDamage(5);
                })
            }
        }
    }


    update(deltaTime: number) {
        // 更新逻辑（如果需要）
        this.node.setPosition(0, 0, 0);
    }
    public attackStart() {
        if (this.collider) {
            this.collider.enabled = true;
        }
    }

    public attackEnd() {
        if (this.collider) {
            this.collider.enabled = false;
        }
    }
}
